import { computed, defineComponent, PropType } from 'vue'
import { Axis, ContextmenuItem } from './interface'
import MenuContent from './MenuContent'
import './style.scss'
const props = {
	axis: {
		type: Object as PropType<Axis>,
		required: true,
	},
	el: {
		type: Object as PropType<HTMLElement>,
		required: true,
	},
	menus: {
		type: Array as PropType<ContextmenuItem[]>,
		required: true,
	},
	removeContextmenu: {
		type: Function,
		required: true,
	},
}
export default defineComponent({
	props,
	setup(props) {
		const style = computed(() => {
			const MENU_WIDTH = 170
			const MENU_HEIGHT = 30
			const DIVIDER_HEIGHT = 11
			const PADDING = 5

			const { x, y } = props.axis as Axis
			const menuCount = props.menus?.filter((menu) => !(menu.divider || menu.hide)).length
			const dividerCount = props.menus?.filter((menu) => menu.divider).length

			const menuWidth = MENU_WIDTH
			const menuHeight = (menuCount ?? 0) * MENU_HEIGHT + (dividerCount ?? 0) * DIVIDER_HEIGHT + PADDING * 2

			const screenWidth = document.body.clientWidth
			const screenHeight = document.body.clientHeight

			return {
				left: screenWidth <= x + menuWidth ? x - menuWidth : x,
				top: screenHeight <= y + menuHeight ? y - menuHeight : y,
			}
		})
		const handleClickMenuItem = (item: ContextmenuItem) => {
			if (item.disable) return
			if (item.children && !item.handler) return
			if (item.handler) item.handler(props.el as HTMLElement)
			props.removeContextmenu && props.removeContextmenu()
		}
		return () => (
			<div>
				<div
					class="mask"
					onContextmenu={(event) => {
						event.stopPropagation()
						event.preventDefault()
						props.removeContextmenu && props.removeContextmenu()
					}}
					onMousedown={() => props.removeContextmenu && props.removeContextmenu()}
				></div>
				<div
					class="contextmenu"
					style={{
						left: style.value.left + 'px',
						top: style.value.top + 'px',
					}}
					onContextmenu={(event) => {
						event.stopPropagation()
						event.preventDefault()
					}}
				>
					<MenuContent menus={props.menus} handleClickMenuItem={handleClickMenuItem} />
				</div>
			</div>
		)
	},
})
